package main

import (
	"database/sql"
	"fmt"
	"github.com/prometheus/common/log"

	_ "github.com/go-sql-driver/mysql"
	"github.com/pkg/errors"
)

type ErrorNoRow struct {
	msg string
}

func (e *ErrorNoRow) Error() string {
	return e.msg
}

var NoRowErr = &ErrorNoRow{msg: "no result"}

func main() {
	err := query()
	if err != nil {
		if errors.Is(err, NoRowErr) {
			log.Info(NoRowErr.Error())
		} else {
			log.Infof("%+v", err)
		}
	}
}

func query() error {
	var (
		id     int
		appKey string
	)

	db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/blog_service")
	if err != nil {
		return errors.Wrap(err, "sql.Open err")
	}
	defer db.Close()

	err = db.QueryRow("select id,app_key from blog_auth where id= ?", 2).Scan(&id, &appKey)
	//sql.ErrNoRows不应该wrap包装后抛给service层，因为只是没有数据，不应该导致应用的错误
	if err != nil {
		if !errors.Is(err, sql.ErrNoRows) {
			return errors.Wrap(err, "db.Query err")
		} else {
			return errors.Wrapf(NoRowErr, "err:%s", err)
		}
	}
	fmt.Println(id, appKey)

	return nil
}
